<template>
  <div class="categories-admin">
    <!-- 面包屑导航 -->
    <Breadcrumb />
    
    <div class="page-header">
      <h1>分类管理</h1>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加分类
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="分类名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入分类名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column prop="name" label="分类名称" min-width="200">
          <template #default="{ row }">
            <div class="category-name">
              <el-icon v-if="row.icon" class="category-icon" :color="row.color">
                <component :is="row.icon" />
              </el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="slug" label="分类标识" width="150" />
        
        <el-table-column prop="description" label="分类描述" min-width="200">
          <template #default="{ row }">
            <span>{{ row.description || '暂无描述' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="articleCount" label="文章数量" width="100">
          <template #default="{ row }">
            <el-tag type="info" size="small">{{ row.articleCount }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="sort" label="排序" width="80" />
        
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button 
              v-if="!row.parentId" 
              type="success" 
              size="small" 
              @click="handleAddChild(row)"
            >
              添加子分类
            </el-button>
            <el-popconfirm
              title="确定要删除这个分类吗？"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="上级分类" prop="parentId" v-if="!isAddChild">
          <el-tree-select
            v-model="form.parentId"
            :data="categoryTree"
            :render-after-expand="false"
            placeholder="请选择上级分类（留空为顶级分类）"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            check-strictly
            clearable
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        
        <el-form-item label="分类标识" prop="slug">
          <el-input v-model="form.slug" placeholder="请输入分类标识（英文字母，用于URL）" />
        </el-form-item>
        
        <el-form-item label="分类图标" prop="icon">
          <el-select v-model="form.icon" placeholder="请选择图标" clearable>
            <el-option label="文档" value="Document" />
            <el-option label="文件夹" value="Folder" />
            <el-option label="标签" value="Collection" />
            <el-option label="通知" value="Bell" />
            <el-option label="新闻" value="Newspaper" />
            <el-option label="政策" value="DocumentCopy" />
            <el-option label="学校" value="School" />
            <el-option label="考试" value="EditPen" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="图标颜色" prop="color">
          <el-color-picker v-model="form.color" />
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number 
            v-model="form.sort" 
            :min="0" 
            :max="999" 
            placeholder="数值越小越靠前"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="分类描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入分类描述（可选）"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Plus, Document, Folder, Collection, Bell, School, EditPen } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import Breadcrumb from '@/components/Breadcrumb.vue'
import { createCategory, updateCategory, deleteCategory, getCategoryList } from '@/api/category'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: null
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分类树数据
const categoryTree = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 弹窗
const dialogVisible = ref(false)
const isAddChild = ref(false) // 是否为添加子分类
const dialogTitle = computed(() => {
  if (isAddChild.value) return '添加子分类'
  return form.id ? '编辑分类' : '添加分类'
})
const submitLoading = ref(false)

// 表单
const formRef = ref()
const form = reactive({
  id: null,
  parentId: null,
  name: '',
  slug: '',
  icon: '',
  color: '#409eff',
  description: '',
  sort: 0,
  status: 1
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ],
  slug: [
    { required: true, message: '请输入分类标识', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '分类标识只能包含字母、数字、下划线和短横线', trigger: 'blur' }
  ]
}

// 构建分类树
const buildCategoryTree = (categories, parentId = null) => {
  return categories
    .filter(cat => cat.parentId === parentId)
    .map(cat => ({
      ...cat,
      children: buildCategoryTree(categories, cat.id)
    }))
}

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    }
    
    // 模拟数据
    const mockCategories = [
      {
        id: 1,
        parentId: null,
        name: '招生政策',
        slug: 'policy',
        icon: 'DocumentCopy',
        color: '#409eff',
        description: '各类招生政策文件',
        sort: 1,
        status: 1,
        articleCount: 25,
        createTime: new Date('2024-01-15')
      },
      {
        id: 2,
        parentId: null,
        name: '招生简章',
        slug: 'brochure',
        icon: 'Document',
        color: '#67c23a',
        description: '各院校招生简章',
        sort: 2,
        status: 1,
        articleCount: 47,
        createTime: new Date('2024-01-16')
      },
      {
        id: 3,
        parentId: null,
        name: '报名指导',
        slug: 'guidance',
        icon: 'EditPen',
        color: '#e6a23c',
        description: '报名流程和注意事项',
        sort: 3,
        status: 1,
        articleCount: 18,
        createTime: new Date('2024-01-17')
      },
      {
        id: 4,
        parentId: null,
        name: '考试信息',
        slug: 'exam',
        icon: 'School',
        color: '#f56c6c',
        description: '考试相关信息',
        sort: 4,
        status: 1,
        articleCount: 32,
        createTime: new Date('2024-01-18')
      },
      {
        id: 5,
        parentId: 4,
        name: '考试大纲',
        slug: 'exam-outline',
        icon: 'Document',
        color: '#909399',
        description: '考试大纲',
        sort: 1,
        status: 1,
        articleCount: 12,
        createTime: new Date('2024-01-19')
      },
      {
        id: 6,
        parentId: 4,
        name: '考试安排',
        slug: 'exam-schedule',
        icon: 'Bell',
        color: '#909399',
        description: '考试时间安排',
        sort: 2,
        status: 1,
        articleCount: 8,
        createTime: new Date('2024-01-20')
      },
      {
        id: 7,
        parentId: null,
        name: '录取信息',
        slug: 'admission',
        icon: 'Collection',
        color: '#909399',
        description: '录取相关信息',
        sort: 5,
        status: 1,
        articleCount: 16,
        createTime: new Date('2024-01-21')
      }
    ]
    
    // 构建树形结构
    const treeData = buildCategoryTree(mockCategories)
    
    tableData.value = treeData
    categoryTree.value = treeData
    pagination.total = mockCategories.length
    
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    status: null
  })
  handleSearch()
}

// 添加
const handleAdd = () => {
  resetForm()
  isAddChild.value = false
  dialogVisible.value = true
}

// 添加子分类
const handleAddChild = (row) => {
  resetForm()
  form.parentId = row.id
  isAddChild.value = true
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  resetForm()
  Object.assign(form, row)
  isAddChild.value = false
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    // 检查是否有子分类
    if (row.children && row.children.length > 0) {
      ElMessage.warning('请先删除子分类')
      return
    }
    
    // 检查是否有文章
    if (row.articleCount > 0) {
      ElMessage.warning('该分类下还有文章，无法删除')
      return
    }
    
    // await deleteCategory(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 状态变更
const handleStatusChange = async (row) => {
  try {
    // await updateCategory({ id: row.id, status: row.status })
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
    row.status = row.status === 1 ? 0 : 1
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (form.id) {
      // await updateCategory(form)
      ElMessage.success('更新成功')
    } else {
      // await createCategory(form)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    getList()
  } catch (error) {
    if (error === false) return // 表单验证失败
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    parentId: null,
    name: '',
    slug: '',
    icon: '',
    color: '#409eff',
    description: '',
    sort: 0,
    status: 1
  })
  isAddChild.value = false
  formRef.value?.clearValidate()
}

// 分页变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  getList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getList()
}

// 格式化日期
const formatDate = (date) => {
  const d = new Date(date)
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${d.getFullYear()}-${month}-${day}`
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.categories-admin {
  padding: 24px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    h1 {
      font-size: 24px;
      color: #303133;
      margin: 0;
    }
  }
  
  .search-card {
    margin-bottom: 16px;
    
    :deep(.el-card__body) {
      padding: 20px;
    }
  }
  
  .table-card {
    :deep(.el-card__body) {
      padding: 20px;
    }
    
    .category-name {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .category-icon {
        font-size: 16px;
      }
    }
    
    .pagination-wrapper {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .categories-admin {
    padding: 16px;
    
    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;
      
      h1 {
        font-size: 20px;
      }
    }
    
    .search-card {
      :deep(.el-form--inline) {
        .el-form-item {
          display: block;
          margin-bottom: 16px;
        }
      }
    }
    
    .table-card {
      :deep(.el-table) {
        font-size: 12px;
      }
    }
  }
}
</style>